#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<signal.h>
#include<sys/time.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>

int count = 0;
pthread_rwlock_t rwlock;


void* wfunc(void* p){
    int i = (long long) p;
    while(1){
        pthread_rwlock_wrlock(&rwlock);
        int t = count;
        printf("write %d , before count = %d, after count is %d\n", i, t, ++ count);
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
    pthread_exit((void*)i);
}

void* rfunc(void* p){
    int i = (long long) p;
    while(1){
        pthread_rwlock_rdlock(&rwlock);
        int t  = count;
        printf("read %d, before count = %d, after count is %d\n", i, t, count);
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
    pthread_exit((void*)i);
}

int main(int argc, char* args[])
{
    int ret;

    pthread_rwlock_init(&rwlock, NULL);
    ret = pthread_rwlock_init(&rwlock, NULL);
    if(ret){
        fprintf(stderr, "pthread_rwlock_init error: %s\n", strerror(ret));
    } 
    pthread_t tid[8];
    
    for(int i = 0; i < 3; i ++){
        pthread_create(&tid[i], NULL, wfunc, (void*)i);
        if(ret){
            fprintf(stderr, "pthread_create error: %s\n", strerror(ret));
        } 
    }

    for(int i = 3; i < 8; i ++){
        pthread_create(&tid[i], NULL, rfunc, (void*)i);
        if(ret){
            fprintf(stderr, "pthread_create error: %s\n", strerror(ret));
        } 
    }

    for(int i = 0; i < 8; i ++){
        pthread_join(tid[i], NULL);
    }
    
    pthread_rwlock_destroy(&rwlock);
    return 0;    
}